package com.example.fw;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.example.tests.PrintPhonesData;
import com.example.utils.ListOf;

public class PrintPhonesHelper extends WebDriverHelperBase {

	private List<PrintPhonesData> cachedContacts;

	public PrintPhonesHelper(ApplicationManager manager) {
		super(manager);
	}

	public List<PrintPhonesData> getContactsAddress() {
		if (cachedContacts == null){
			rebuildCache();
		}
		return cachedContacts;
	}
	
	private void rebuildCache(){
		cachedContacts = new ListOf<PrintPhonesData>();
		int trIndex = 1;
		String contactName[];
		manager.navigateTo().gotoPrintPhonesPage();
		
		List<WebElement> colid = 
				driver.findElements(By.xpath("//*[@id='view']/tbody/tr["+trIndex+"]/td"));
		do{
			for (int indx = 1; indx <= colid.size(); indx++) {
				PrintPhonesData contactAddress = new PrintPhonesData();
				WebElement l_firstname = 
						driver.findElement(By.xpath("//*[@id='view']/tbody/tr["+trIndex+"]/td["+indx+"]/b/text()"));
				contactName = l_firstname.toString().split("\\s+");
				
				contactAddress.withFirstName(contactName[0]);
				contactAddress.withLastName(contactName[1]);

				WebElement l_homephone = 
						driver.findElement(By.xpath(".//*[@id='view']/tbody/tr["+trIndex+"]/td["+indx+"]/text()[2]"));
				contactAddress.withHomePhone(l_homephone.toString().replaceAll("([M|H][:]\\s)", ""));

				WebElement l_mobylephone = 
						driver.findElement(By.xpath(".//*[@id='view']/tbody/tr["+trIndex+"]/td["+indx+"]/text()[3]"));
				contactAddress.withHomePhone(l_mobylephone.toString().replaceAll("([M|H][:]\\s)", ""));

				cachedContacts.add(contactAddress);
	 		}
			trIndex++;
			colid = driver.findElements(By.xpath("//*[@id='view']/tbody/tr["+(trIndex)+"]/td"));
		} while ( colid.size() > 0 );
	}
}
